#include "httplib.h"
#include <thread>
#include "FFmpegDemuxer.h"

#define HTTP_API __declspec(dllexport)

#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
	typedef const char* (__stdcall* MsgCallBack)(const char* path, const char* method, const char* body);

	httplib::Server server;
	MsgCallBack callback = nullptr;

	void any_request_callback(const httplib::Request& req, httplib::Response& res)
	{
		if (callback)
		{
			const char* responseStr = callback(req.path.c_str(), req.method.c_str(), req.body.c_str());
			res.status = 200;
			res.set_content(responseStr, "application/json");
		}
	}

	void th_listen(const char* ip, int port)
	{
		server.listen(ip, port);
	}


	HTTP_API bool http_startup(const char* ip, int port)
	{
		if (server.is_running())
			server.stop();
		server.set_any_request_callback(any_request_callback);
		std::thread(th_listen,ip,port).detach();
		return true;
	}

	HTTP_API void set_callback(MsgCallBack _callback)
	{
		callback = _callback;
	}


	HTTP_API void http_stop()
	{
		if (server.is_running())
			server.stop();
	}

	HTTP_API const char* http_post_upload(
		const char* ip, int port, const char* endpoint,
		const char* name, const char* content, int content_len, const char* filename, const char* contentType)
	{
		httplib::MultipartFormData mf;
		memset(&mf, 0, sizeof(mf));
		mf.name = std::string(name);
		mf.content = std::string(content, content_len);
		mf.filename = std::string(filename);
		mf.content_type = std::string(contentType);
		httplib::MultipartFormDataItems items = { mf };

		httplib::Client cli(ip, port);
		return cli.Post(endpoint, items)->body.c_str();
	}


	HTTP_API void* getDemuxerInstance(const char* mrl)
	{
		return new FFmpegDemuxer(mrl);
	}

	HTTP_API void releaseDemuxerInstance(void* instance)
	{
		delete (FFmpegDemuxer*)instance;
	}

	HTTP_API bool Demux(void* instance,uint8_t** ppVideo, int* pnVideoBytes, int64_t* pts = NULL)
	{
		return ((FFmpegDemuxer*)instance)->Demux(ppVideo, pnVideoBytes, pts);
	}

#ifdef __cplusplus
}
#endif // __cplusplus

